﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Mozlite.Components
{
    /// <summary>
    /// 查询基类。
    /// </summary>
    public abstract class BaseQuery
    {
        /// <summary>
        /// 初始化类<see cref="BaseQuery"/>。
        /// </summary>
        public BaseQuery()
        {
            Context = AppContext.Current;
            PageSize = Context.PageSize;
            Fields = "*";
            Self = Context.User;
        }

        /// <summary>
        /// 应用程序上下文。
        /// </summary>
        protected AppContext Context { get; private set; }
        /// <summary>
        /// 获取当前登录用户。
        /// </summary>
        protected User Self { get; private set; }
        /// <summary>
        /// 页面代码。
        /// </summary>
        public int PageIndex { get; set; }
        /// <summary>
        /// 页面显示记录数。
        /// </summary>
        public int PageSize { get; set; }
        /// <summary>
        /// 查询的列。
        /// </summary>
        public string Fields { get; set; }
        /// <summary>
        /// 获取或设置排序列。
        /// </summary>
        public string OrderBy { get; set; }
        /// <summary>
        /// 附加条件。
        /// </summary>
        /// <returns>获取附加条件。</returns>
        protected abstract string AppendWheres();
        /// <summary>
        /// 获取参数匿名类型。
        /// </summary>
        /// <returns>返回参数匿名类型。</returns>
        protected abstract object AppendParameters();
        /// <summary>
        /// 获取分页列表。
        /// </summary>
        /// <typeparam name="T">实例类型。</typeparam>
        /// <param name="size">返回总记录数。</param>
        /// <returns>返回实例列表。</returns>
        public abstract List<T> Load<T>(out int size) where T : class,new();
        /// <summary>
        /// 获取分页列表。
        /// </summary>
        /// <typeparam name="T">实例类型。</typeparam>
        /// <param name="tables">表格语句，可以包含“inner join...on”等等语句。</param>
        /// <param name="size">返回总记录数。</param>
        /// <returns>返回实例列表。</returns>
        protected List<T> Fetch<T>(string tables, out int size) where T : class,new()
        {
            Guard.IsNotNullOrEmpty(OrderBy, "OrderBy");
            string where = AppendWheres();
            if(where.HasValue())
                where = " WHERE " + where;
            string sql = "SELECT {0} FROM {1}{2} ORDER BY {3}".FormatWith(Fields, tables, where, OrderBy);
            return Database.Fetch<T>(PageIndex, PageSize, sql, AppendParameters(), out size);
        }
    }
}
